package util

import (
	"fmt"
	"sync"
	"time"
)

func Run(cfg *Config, suffix string) {
	MyLogger.PrintlnWithConsole("当前操作后缀名：", suffix)
	MFIch := make(chan MediaFileInfo)
	FileSum := 0
	FileIndex := 0
	files, err := SearchFile(cfg.InputPath, suffix, cfg.IsSubDir)
	if err != nil {
		MyLogger.Println(err)
		return
	}

	FileSum = len(files)
	MyLogger.PrintfWithConsole("找到%d个文件。\n", FileSum)
	if FileSum == 0 {
		MyLogger.Println("没有需要处理的文件")
		return
	}

	//读取文件信息
	go func() {
		for _, v := range files {
			mfi, ok := GetMediaFileInfo(v, suffix)
			if ok {
				MFIch <- mfi
			}
		}
		close(MFIch)
	}()
	var lock sync.Mutex
	var wg sync.WaitGroup
	//复制或移动文件

	for item := range MFIch {
		mfi := item
		wg.Add(1)
		go func() {
			status, err := Doing(cfg, mfi)
			lock.Lock()
			FileIndex += 1
			MyLogger.PrintfWithConsole("进度：%v/%v(%0.2f%%)\t状态：%v\t错误信息：%v\t剩余待处理文件数量：%v\n",
				FileIndex,
				FileSum,
				float64(FileIndex)/float64(FileSum)*100,
				status,
				err,
				FileSum-FileIndex)
			lock.Unlock()
			wg.Done()
		}()
	}
	wg.Wait()
}

func Doing(cfg *Config, mfi MediaFileInfo) (string, error) {
	oldName := mfi.FileFullName
	status := "失败"
	MyLogger.Printf("文件名： %v\t是否有拍摄时间：%v\t拍摄时间：%v\t修改时间：%v\n", mfi.FileFullName, mfi.HasExif, mfi.TokenTime, mfi.ModTime)
	var fileTime time.Time
	if mfi.HasExif {
		fileTime = mfi.TokenTime
	} else {
		if !cfg.IsDoNoExitDate {
			status = "配置跳过"
			//MyLogger.Printf("%v : %v", status, oldName)
			return status, fmt.Errorf(status)
		}
		fileTime = mfi.ModTime
	}

	newName := cfg.OutputPath + TimeString(cfg.NewDirMode1, fileTime) + cfg.Prefix
	if cfg.IsRename {
		newName = newName + TimeString(cfg.NewFilenameFormat, fileTime)
	} else {
		newName = newName + mfi.FileName
	}
	newName = newName + cfg.Suffix + mfi.Ext
	ok, err := RenameFile(oldName, newName, cfg.IsMove)
	if ok {
		status = "成功"
	}
	//MyLogger.Printf("%v : %v    %v", status, oldName, newName)
	return status, err
}
